#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
共享日志工具模块
提供统一的队列日志处理器和相关功能
"""

import logging
import queue
import threading
from typing import Dict, Any, Optional

# 添加SUCCESS级别
SUCCESS_LEVEL = 25  # 在INFO(20)和WARNING(30)之间
logging.addLevelName(SUCCESS_LEVEL, 'SUCCESS')

def success(self, message, *args, **kwargs):
    """SUCCESS级别的日志方法"""
    if self.isEnabledFor(SUCCESS_LEVEL):
        self._log(SUCCESS_LEVEL, message, args, **kwargs)

# 将success方法添加到Logger类
logging.Logger.success = success


class QueueLogHandler(logging.Handler):
    """队列日志处理器，将日志消息发送到队列中"""
    
    def __init__(self, log_queue: queue.Queue):
        super().__init__()
        self.log_queue = log_queue
    
    def emit(self, record):
        """发送日志记录到队列"""
        try:
            log_entry = {
                'timestamp': record.created,
                'level': record.levelname,
                'message': record.getMessage()
            }
            self.log_queue.put(log_entry)
        except Exception:
            # 避免在日志处理过程中出现异常
            self.handleError(record)


class LogManager:
    """日志管理器，提供统一的日志配置和管理"""
    
    def __init__(self):
        self.log_queue = queue.Queue()
        self._setup_logger()
    
    def _setup_logger(self):
        """设置日志配置"""
        # 设置根日志器
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        
        # 清除现有的处理器，避免重复
        self.logger.handlers.clear()
        
        # 添加控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        console_handler.setFormatter(console_formatter)
        self.logger.addHandler(console_handler)
        
        # 添加队列处理器
        queue_handler = QueueLogHandler(self.log_queue)
        queue_handler.setLevel(logging.INFO)
        self.logger.addHandler(queue_handler)
    
    def get_logger(self, name: str) -> logging.Logger:
        """获取指定名称的日志器"""
        return logging.getLogger(name)
    
    def get_log_queue(self) -> queue.Queue:
        """获取日志队列"""
        return self.log_queue
    
    def get_logs(self, max_logs: int = 100) -> list:
        """获取日志条目列表"""
        logs = []
        count = 0
        
        while count < max_logs and not self.log_queue.empty():
            try:
                log_entry = self.log_queue.get_nowait()
                logs.append(log_entry)
                count += 1
            except queue.Empty:
                break
        
        return logs
    
    def clear_logs(self):
        """清空日志队列"""
        while not self.log_queue.empty():
            try:
                self.log_queue.get_nowait()
            except queue.Empty:
                break


# 全局日志管理器实例
_log_manager = None
_lock = threading.Lock()


def get_log_manager() -> LogManager:
    """获取全局日志管理器实例（单例模式）"""
    global _log_manager
    
    if _log_manager is None:
        with _lock:
            if _log_manager is None:
                _log_manager = LogManager()
    
    return _log_manager


def get_logger(name: str) -> logging.Logger:
    """获取日志器"""
    return get_log_manager().get_logger(name)


def get_log_queue() -> queue.Queue:
    """获取日志队列"""
    return get_log_manager().get_log_queue()


def get_logs(max_logs: int = 100) -> list:
    """获取日志条目"""
    return get_log_manager().get_logs(max_logs)


def clear_logs():
    """清空日志"""
    get_log_manager().clear_logs()


def setup_console_logger(logger_name: str = None):
    """为指定的日志器设置控制台处理器"""
    logger = logging.getLogger(logger_name) if logger_name else logging.getLogger()
    logger.setLevel(logging.INFO)
    
    # 清除现有的处理器，避免重复
    logger.handlers.clear()
    
    # 添加控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)
    
    return logger


# 为了向后兼容，提供直接的队列访问
log_queue = get_log_queue()
